package gw.com.android.ui.onlive;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.gwtsz.gts2.hx.R;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.presenter.AdsData;
import gw.com.android.presenter.NoviceWelfarePresenter;
import gw.com.android.presenter.http.DiscussRequest;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.dialog.ImageOperationPopWindow;
import gw.com.android.ui.views.ImageWatcher;
import gw.com.android.utils.IOUtils;
import gw.com.android.utils.PackStatis;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.util.DeviceUtil;

/**
 * 晒单列表
 *
 * @author jett
 * @since 2017-11-17.
 */
public class DiscussFragment extends Fragment {

    private TextView tv_get_all, tv_get_guest, tv_get_analyst, tv_get_best;
    private View v_tag_1, v_tag_2, v_tag_3, v_tag_4;
    private QuanziListFragment quanziListFragmentPost, quanziListFragmentGuest, quanziListFragmentBest, quanziListFragmentAnalyst;
    private View ll_back_to_top;
    private View welfareView; // 新手福利弹窗小广告

    private ImageWatcher imageWatcher;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_discuss, container, false);
        initView(root);
        return root;
    }

    private void initView(View root) {
        ll_back_to_top = root.findViewById(R.id.ll_back_to_top);
        ll_back_to_top.setVisibility(View.GONE);
        ll_back_to_top.setAlpha(0);
        ll_back_to_top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollListToTop();
            }
        });

        imageWatcher = (ImageWatcher) getActivity().findViewById(R.id.v_image_watcher);
        imageWatcher.setOnPictureLongPressListener(new LongPressListener());

        View addView = root.findViewById(R.id.add_discuss);
        addView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_REAL) {
                    new ToastPopWindow(getContext(), AppMain.getApp().getString(R.string.home_discuss_not_real_2)).show();
                    return;
                }
                ActivityManager.showDiscussAdd(getActivity());
            }
        });

        //4个分类按钮
        tv_get_all = (TextView) root.findViewById(R.id.tv_get_all);
        tv_get_guest = (TextView) root.findViewById(R.id.tv_get_guest);
        tv_get_analyst = (TextView) root.findViewById(R.id.tv_get_analyst);
        tv_get_best = (TextView) root.findViewById(R.id.tv_get_best);

        //4个短标记
        v_tag_1 = root.findViewById(R.id.v_tag_1);
        v_tag_2 = root.findViewById(R.id.v_tag_2);
        v_tag_3 = root.findViewById(R.id.v_tag_3);
        v_tag_4 = root.findViewById(R.id.v_tag_4);

        //分别添加事件
        tv_get_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshButtonColor(v);
                refreshSep(v);
                showQuanziFragmentPost();
            }
        });
        tv_get_guest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshButtonColor(v);
                refreshSep(v);
                showQuanziFragmentGuest();
            }
        });
        tv_get_analyst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshButtonColor(v);
                refreshSep(v);
                showQuanziFragmentAnalyst();
            }
        });
        tv_get_best.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshButtonColor(v);
                refreshSep(v);
                showQuanziFragmentBest();
            }
        });

        showQuanziFragmentPost();// 初始状态，显示动态，只展示帖子
        // 显示新手福利弹窗广告
        if (NoviceWelfarePresenter.getInstance().needShow()) {
            final AdsData.PicData adData = NoviceWelfarePresenter.getInstance().getAdData();
            AppMain.getApp().getHandler().post(new Runnable() {
                @Override
                public void run() {
                    showNoviceWelfare(adData.title, adData.link);
                }
            });
        }
    }

    //想个办法切换这4个Fragment
    private List<Fragment> fragments = new ArrayList<>();//新建容量为4的fragment数组
    private int currentType = DiscussRequest.TRADE_TYPE_ALL;

    /**
     * 动态：产品大佬说，只展示用户发帖，不展示晒单内容··所以。。
     */
    private void showQuanziFragmentPost() {
        PackStatis.getToService("clickTrends", PackStatis.EventCategory.CIRCLE.getValue(), null, null);
        FragmentManager fm = getChildFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        if (quanziListFragmentPost == null) {
            quanziListFragmentPost = new QuanziListFragmentPost();
            quanziListFragmentPost.setImageWatcher(imageWatcher);
            ft.add(R.id.layout_recycler_view, quanziListFragmentPost);
            //new出来之后，都要加入一个fragment的数组，然后如果显示了它，就要把其他的都隐藏
            fragments.add(quanziListFragmentPost);
            quanziListFragmentPost.setOnScrollCallback(onScrollCallback);
        }
        ft.show(quanziListFragmentPost);

        //如果是在当前分类，并且又点了一次
        //排除类型切换的情况
        if (currentType == DiscussRequest.TRADE_TYPE_ALL)
            quanziListFragmentPost.refreshListData();
        currentType = DiscussRequest.TRADE_TYPE_ALL;

        //隐藏其他
        for (int i = 0; i < fragments.size(); i++) {
            if (fragments.get(i) != quanziListFragmentPost) {
                ft.hide(fragments.get(i));
            }
        }
        hideBackToTop();


        ft.commit();
        quanziListFragmentPost.refreshFollowedAnalystForPartialRefresh(false);
    }

    /**
     * 显示 客户晒单帖子的fragment
     */
    private void showQuanziFragmentGuest() {
        PackStatis.getToService("clickBask2", PackStatis.EventCategory.CIRCLE.getValue(), null, null);
        FragmentManager fm = getChildFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        if (quanziListFragmentGuest == null) {
            quanziListFragmentGuest = new QuanziListFragmentGuest();
            quanziListFragmentGuest.setImageWatcher(imageWatcher);
            ft.add(R.id.layout_recycler_view, quanziListFragmentGuest);
            fragments.add(quanziListFragmentGuest);
            quanziListFragmentGuest.setOnScrollCallback(onScrollCallback);
        }
        ft.show(quanziListFragmentGuest);
        if (currentType == DiscussRequest.TRADE_TYPE_GUEST)
            quanziListFragmentGuest.refreshListData();
        currentType = DiscussRequest.TRADE_TYPE_GUEST;
        //隐藏其他
        for (int i = 0; i < fragments.size(); i++) {
            if (fragments.get(i) != quanziListFragmentGuest) {
                ft.hide(fragments.get(i));
            }
        }
        hideBackToTop();
        ft.commit();
        quanziListFragmentGuest.refreshFollowedAnalystForPartialRefresh(false);
    }

    /**
     * 显示 客户晒单帖子的fragment
     */
    private void showQuanziFragmentBest() {
        PackStatis.getToService("clickEssence", PackStatis.EventCategory.CIRCLE.getValue(), null, null);
        FragmentManager fm = getChildFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        if (quanziListFragmentBest == null) {
            quanziListFragmentBest = new QuanziListFragmentBest();
            quanziListFragmentBest.setImageWatcher(imageWatcher);
            ft.add(R.id.layout_recycler_view, quanziListFragmentBest);
            fragments.add(quanziListFragmentBest);
            quanziListFragmentBest.setOnScrollCallback(onScrollCallback);
        }
        ft.show(quanziListFragmentBest);
        if (currentType == DiscussRequest.TRADE_TYPE_BEST)
            quanziListFragmentBest.refreshListData();
        currentType = DiscussRequest.TRADE_TYPE_BEST;
        //隐藏其他
        for (int i = 0; i < fragments.size(); i++) {
            if (fragments.get(i) != quanziListFragmentBest) {
                ft.hide(fragments.get(i));
            }
        }
        hideBackToTop();
        ft.commit();
        quanziListFragmentBest.refreshFollowedAnalystForPartialRefresh(false);
    }

    /**
     * 只看分析师
     */
    private void showQuanziFragmentAnalyst() {
        PackStatis.getToService("clickOnlyTeachers", PackStatis.EventCategory.CIRCLE.getValue(), null, null);
        FragmentManager fm = getChildFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        if (quanziListFragmentAnalyst == null) {
            quanziListFragmentAnalyst = new QuanziListFragmentAnalyst();
            quanziListFragmentAnalyst.setImageWatcher(imageWatcher);
            ft.add(R.id.layout_recycler_view, quanziListFragmentAnalyst);
            fragments.add(quanziListFragmentAnalyst);
            quanziListFragmentAnalyst.setOnScrollCallback(onScrollCallback);
        }
        ft.show(quanziListFragmentAnalyst);
        if (currentType == DiscussRequest.TRADE_TYPE_ANALYST)
            quanziListFragmentAnalyst.refreshListData();
        currentType = DiscussRequest.TRADE_TYPE_ANALYST;
        //隐藏其他
        for (int i = 0; i < fragments.size(); i++) {
            if (fragments.get(i) != quanziListFragmentAnalyst) {
                ft.hide(fragments.get(i));
            }
        }
        hideBackToTop();
        ft.commit();
        quanziListFragmentAnalyst.refreshFollowedAnalystForPartialRefresh(false);
    }


    private int colorSelected = Color.parseColor("#F8A916");
    private int colorNotSelected = Color.parseColor("#666666");

    /**
     * 4个类别按钮，要每次只能显示一个橙色的选中状态,其他3个都是黑色字体
     *
     * @param clickView
     */
    private void refreshButtonColor(View clickView) {
        if (clickView == tv_get_all) {
            tv_get_all.setTextColor(colorSelected);
            tv_get_guest.setTextColor(colorNotSelected);
            tv_get_analyst.setTextColor(colorNotSelected);
            tv_get_best.setTextColor(colorNotSelected);
        } else if (clickView == tv_get_analyst) {
            tv_get_all.setTextColor(colorNotSelected);
            tv_get_guest.setTextColor(colorNotSelected);
            tv_get_analyst.setTextColor(colorSelected);
            tv_get_best.setTextColor(colorNotSelected);
        } else if (clickView == tv_get_guest) {
            tv_get_all.setTextColor(colorNotSelected);
            tv_get_guest.setTextColor(colorSelected);
            tv_get_analyst.setTextColor(colorNotSelected);
            tv_get_best.setTextColor(colorNotSelected);
        } else if (clickView == tv_get_best) {
            tv_get_all.setTextColor(colorNotSelected);
            tv_get_guest.setTextColor(colorNotSelected);
            tv_get_analyst.setTextColor(colorNotSelected);
            tv_get_best.setTextColor(colorSelected);
        }
    }

    /**
     * 4个按钮下面的标记view
     *
     * @param clickView
     */
    private void refreshSep(View clickView) {
        if (clickView == tv_get_all) {
            v_tag_1.setVisibility(View.VISIBLE);
            v_tag_2.setVisibility(View.INVISIBLE);
            v_tag_3.setVisibility(View.INVISIBLE);
            v_tag_4.setVisibility(View.INVISIBLE);
        } else if (clickView == tv_get_best) {
            v_tag_1.setVisibility(View.INVISIBLE);
            v_tag_2.setVisibility(View.INVISIBLE);
            v_tag_3.setVisibility(View.VISIBLE);
            v_tag_4.setVisibility(View.INVISIBLE);
        } else if (clickView == tv_get_guest) {
            v_tag_1.setVisibility(View.INVISIBLE);
            v_tag_2.setVisibility(View.VISIBLE);
            v_tag_3.setVisibility(View.INVISIBLE);
            v_tag_4.setVisibility(View.INVISIBLE);
        } else if (clickView == tv_get_analyst) {
            v_tag_1.setVisibility(View.INVISIBLE);
            v_tag_2.setVisibility(View.INVISIBLE);
            v_tag_3.setVisibility(View.INVISIBLE);
            v_tag_4.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 长按图片 ，保存图片
     */
    private class LongPressListener implements ImageWatcher.OnPictureLongPressListener {
        @Override
        public void onPictureLongPress(ImageView v, final String url, int pos) {
            new ImageOperationPopWindow(getActivity(), new ImageOperationPopWindow.OnSaveListener() {
                @Override
                public void onSave() {
                    saveImage(url);
                }
            }).show();
        }
    }

    private void saveImage(String url) {
        final BaseActivity activity = (BaseActivity) getActivity();
        if (activity == null) {
            return;
        }
        activity.showLoading();

        String fileName = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date());
        final File file = new File(GTConfig.instance().getRootDirectory() + "/image/" + fileName + ".jpg");

        Glide.with(getActivity()).load(url).downloadOnly(new SimpleTarget<File>() {
            @Override
            public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
                activity.hideLoading();
                if (resource != null && resource.length() > 0) {
                    boolean copy = IOUtils.copy(resource, file);
                    if (copy) {
                        Uri uri = Uri.fromFile(file);
                        getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                        new ToastPopWindow(getContext(), AppMain.getAppString(R.string.home_save_success_title)).show();
                        return;
                    }
                }
                new ToastPopWindow(getContext(), AppMain.getAppString(R.string.home_save_fail_title)).show();
            }

            @Override
            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                activity.hideLoading();
                new ToastPopWindow(getContext(), AppMain.getAppString(R.string.home_save_fail_title));
            }
        });
    }


    /**
     * 返回按钮监听
     */
    public boolean onBackPressed() {
        if (imageWatcher != null && imageWatcher.getVisibility() == View.VISIBLE) {
            imageWatcher.handleBackPressed();
            return true;
        }
        return false;
    }

    public void scrollListToTop() {
        switch (currentType) {
            case DiscussRequest.TRADE_TYPE_ALL:
                quanziListFragmentPost.scrollListToTop();
                break;
            case DiscussRequest.TRADE_TYPE_GUEST:
                quanziListFragmentGuest.scrollListToTop();
                break;
            case DiscussRequest.TRADE_TYPE_BEST:
                quanziListFragmentBest.scrollListToTop();
                break;
            case DiscussRequest.TRADE_TYPE_ANALYST:
                quanziListFragmentAnalyst.scrollListToTop();
                break;
            default:
                break;
        }
    }

    private QuanziListFragment.OnScrollCallback onScrollCallback = new QuanziListFragment.OnScrollCallback() {
        @Override
        public void onScroll(int p) {
            if (p >= 3)// item超过3个，就显示回到顶部
                //给这里加动画，不要让他的出现和消失这么突兀
                showBackToTop();
            else
                hideBackToTop();
        }

    };

    private boolean ifShowing = false;//是否是显示状态

    ObjectAnimator showAnimator, hideAnimator;

    private void cancelAnimator() {
        if (null != showAnimator)
            showAnimator.cancel();
        if (null != hideAnimator)
            hideAnimator.cancel();
    }

    private void showBackToTop() {
        if (ifShowing) return;
        //取消当前动画
        cancelAnimator();
        if (null == showAnimator) {
            showAnimator = ObjectAnimator.ofFloat(ll_back_to_top, "alpha", 0.0f, 1.0f).setDuration(300);
            showAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationStart(Animator animation) {
                    ll_back_to_top.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    ifShowing = true;
                }
            });
        }
        showAnimator.start();
    }

    private void hideBackToTop() {
        if (!ifShowing) return;
        cancelAnimator();
        if (null == hideAnimator) {
            hideAnimator = ObjectAnimator.ofFloat(ll_back_to_top, "alpha", 1.0f, 0.0f).setDuration(300);
            hideAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    ll_back_to_top.setVisibility(View.GONE);
                    ifShowing = false;
                }

                @Override
                public void onAnimationStart(Animator animation) {
                    super.onAnimationStart(animation);
                }
            });
        }
        hideAnimator.start();
    }

    /**
     * 新手福利小弹窗的广告哇
     */
    public void showNoviceWelfare(String title, String link) {
        View mRootView = getView();
        if (mRootView != null && welfareView == null && (mRootView instanceof RelativeLayout)) {
            welfareView = NoviceWelfarePresenter.getInstance().createView(getActivity(), title, link);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.CENTER_HORIZONTAL);
            params.topMargin = DeviceUtil.instance().dip2px(80, AppMain.getApp());
            ((RelativeLayout) mRootView).addView(welfareView, params);
        }
    }

    public void hideNoviceWelfare() {
        if (welfareView != null) {
            AnimatorSet set = (AnimatorSet) welfareView.getTag();
            if (set != null) {
                set.cancel();
            }
            welfareView.setTag(null);
            ViewGroup parent = (ViewGroup) welfareView.getParent();
            if (parent != null) {
                parent.removeView(welfareView);
                welfareView = null;
            }
        }
    }

}
